package cn.btks.resultintegration.catalog.service.impl;

import cn.btks.commonserver.result.ResultState;
import cn.btks.commonserver.result.StateInfo;
import cn.btks.commonserver.util.FileUtil;
import cn.btks.commonserver.util.JwtUtil;
import cn.btks.resultintegration.achievements.pojo.AchievementsFile;
import cn.btks.resultintegration.catalog.pojo.PolicyFile;
import cn.btks.resultintegration.catalog.repository.PolicyFileRepository;
import cn.btks.resultintegration.catalog.service.PolicyFileService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author lijun
 * @CompileUnit 测绘地理信息分院研发中心
 * @Date 2023/10/10 10:36
 */
@Service
public class PolicyFileServiceImpl implements PolicyFileService {

    @Autowired
    PolicyFileRepository policyFileRepository;

    @Override
    public PolicyFile findById(Long id) {
        Optional<PolicyFile> optional = policyFileRepository.findById(id);
        return optional.get();
    }

    @Override
    public List<PolicyFile> findByName(String fileName) {
        return policyFileRepository.findAllByFileName(fileName);
    }

    @Override
    public List<PolicyFile> findByCatalogId(Long catalogId) {
        return policyFileRepository.findAllByCatalogId(catalogId);
    }

    @Override
    public ResultState save(PolicyFile policyFile, List<MultipartFile> list, HttpServletRequest request) throws Exception {
        if(Objects.nonNull(policyFile) && CollectionUtils.isNotEmpty(list)){
            //从header取出token
            String token = request.getHeader("token");
            String userId = org.apache.commons.lang3.StringUtils.EMPTY;
            String userName = org.apache.commons.lang3.StringUtils.EMPTY;
            if(!StringUtils.isEmpty(token)){
                Map<String, Object> tokenInfo = JwtUtil.getTokenInfo(request, JwtUtil.jwtsSecret);
                if(MapUtils.isNotEmpty(tokenInfo)){
                    userId = tokenInfo.get("id").toString();
                    userName = tokenInfo.get("username").toString();
                }
            }
            String filePath = "res/achievements/policy/";
            for (int i = 0; i < list.size(); i++) {
                String uuid = UUID.randomUUID().toString();
                PolicyFile file = new PolicyFile();
                String fjName = uuid + "_" + list.get(i).getOriginalFilename();
                String originalFileName = list.get(i).getOriginalFilename();
                String pathname = request.getSession(true).getServletContext().getRealPath("//") + filePath + fjName;
                String filePathFinal = filePath + fjName;
                System.out.println(request.getSession(true).getServletContext().getRealPath("//"));
                if (FileUtil.fileUpload(list.get(i), pathname)) {
                    return new ResultState(StateInfo.Upload_File_ERROR.getCode(), StateInfo.Upload_File_ERROR.getMsg());
                }
                String suffix = filePathFinal.substring(filePathFinal.lastIndexOf(".") + 1);
                if (!StringUtils.isEmpty(suffix)) {
                    file.setFileType(suffix);
                }
                file.setFileSize(list.get(i).getSize() / 1024);
                file.setFilePath(filePathFinal);
                file.setFileName(originalFileName);
                file.setCatalogId(policyFile.getCatalogId());
                file.setCreateId(userId);
                file.setCreateName(userName);
                file.setCreateTime(new Date());
                policyFileRepository.save(file);
            }
            return new ResultState(StateInfo.Upload_File_OK.getCode(), StateInfo.Upload_File_OK.getMsg());
        }
        return new ResultState(StateInfo.Upload_File_ERROR.getCode(), StateInfo.Upload_File_ERROR.getMsg());
    }

    @Override
    public ResultState delete(Long id) {
        Optional<PolicyFile> optional = policyFileRepository.findById(id);
        if(optional.isPresent()){
            policyFileRepository.deleteById(id);
            return new ResultState(StateInfo.DELETE_OK.getCode(), StateInfo.DELETE_OK.getMsg());
        }
        return new ResultState(StateInfo.DELETE_ERROR.getCode(), StateInfo.DELETE_ERROR.getMsg());
    }
}
